package server.handler;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;

/**
 * selectionKey 消费 handler
 *
 * @author srh
 * @date 2020/10/18
 **/
public abstract class AbstractSelectionKeyHandler {

    protected Selector selector;
    protected ByteBuffer writeBuffer;
    protected ByteBuffer readBuffer;

    public void config(Selector selector, ByteBuffer readBuffer, ByteBuffer writeBuffer) {
        this.selector = selector;
        this.readBuffer = readBuffer;
        this.writeBuffer = writeBuffer;
    }

    public void execute(SelectionKey selectionKey) {
        if (preHandler(selectionKey)) {
            handler(selectionKey);
        }
    }

    /**
     * 各 handler 处理校验规则
     *
     * @param selectionKey
     * @return
     */
    public abstract boolean preHandler(SelectionKey selectionKey);

    /**
     * 消费 selectionKey
     *
     * @param selectionKey
     */
    public abstract void handler(SelectionKey selectionKey);

}
